list -2 1 -3 4 -1 2 1 -5 4 current -2 1 0 4 3 5 6 1 5 m -2 1 1 4 4 5 6 6 6
动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 dp = [nums[0] for i in range(len(nums))] max_result = nums[0] # 最开始的是nums[0],后面如果是负数肯定更小,如果是整数肯定变大 for i in range(1, len(nums)): if dp[i-1] < 0: dp[i] = nums[i] else: dp[i] = dp[i-1] + nums[i] if max_result < dp[i]: max_result = dp[i] return max_result
直接方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 current = nums[0] m = current for i in range(1, len(nums)): if current < 0: current = 0 current += nums[i] m = max(current, m) return m